package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.alter.ValidateConstraint;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user,HttpSession session) {
        //1.获取手机号码
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //设置4位的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //日志显示验证码,以便于我们模拟
            log.info("验证码={}", code);
            //存储验证码
             //session.setAttribute(phone, code);
            //在redis中存储验证码
            redisTemplate.opsForValue().set(phone,code,30, TimeUnit.SECONDS);
            return R.success();
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号,验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //再从Session中获取保存的验证码
//        Object attribute = session.getAttribute(phone);
        //从redis获取验证码
        Object redisCode = redisTemplate.opsForValue().get(phone);
        //进行验证码的对比
        if (redisCode != null && redisCode.equals(code)) {
            //对比成功，就成功登录
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);

            User user = userService.getOne(wrapper);
            //判断是否为新用户，是新用户就存在数据库，
            if (user == null) {
                user = new User();
                user.setStatus(1);
                user.setPhone(phone);
                userService.save(user);
            }
            //存入到Session中
            session.setAttribute("user",user.getId());
            //删除redis验证
            redisTemplate.delete(phone);
           return R.success();
        }
        return R.error("登录失败");
    }
}


